package cn.faster.config.security.shiro.realm;

import cn.faster.common.utils.sys.redis.MyByteSource;
import cn.faster.sys.entity.*;
import cn.faster.sys.service.*;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.ArrayList;
import java.util.List;

/**
 * description: UserRealm
 * date: 2021/6/9 10:04
 * author: XiaoCoder
 * version: 1.0
 */
@Log4j2
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysUserRoleCenterService sysUserRoleCenterService;

    @Autowired
    private SysRoleMenuCenterService sysRoleMenuCenterService;


    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        SysUser sysUser = (SysUser) principals.getPrimaryPrincipal();

        List<SysUserRoleCenter> sysUserRoleCenters = sysUserRoleCenterService.getBaseMapper().selectList(new QueryWrapper<SysUserRoleCenter>().eq("u_id", sysUser.getId()));  // 根据用户id查询所有的role

        List<Long> roleIds = new ArrayList<>();// 获取所有的用户信息id存入集合中

        sysUserRoleCenters.forEach(t -> roleIds.add(t.getRId()));

        List<SysRole> sysRoles = sysRoleService.getBaseMapper().selectBatchIds(roleIds);
        if (!CollectionUtils.isEmpty(sysRoles)) {
            ArrayList<String> roleStrings = new ArrayList<>();
            sysRoles.forEach(t -> {
                if (!roleStrings.contains(t.getName())) {
                    roleStrings.add(t.getName());

                    List<SysRoleMenuCenter> sysRoleMenuCenters = sysRoleMenuCenterService.getBaseMapper().selectList(new QueryWrapper<SysRoleMenuCenter>().eq("r_id", t.getId()));// 获取role对应的权限ids

                    ArrayList<Long> menuIds = new ArrayList<>();
                    sysRoleMenuCenters.forEach(roleMenuCenter -> menuIds.add(roleMenuCenter.getMId()));// 获取所有的Menu的id

                    List<SysMenu> sysMenus = sysMenuService.getBaseMapper().selectBatchIds(menuIds);// 获取到当前用户的role下面的所有Menu
                    ArrayList<String> menuStrings = new ArrayList<>();
                    sysMenus.forEach(menu -> menuStrings.add(menu.getPerms()));
                    simpleAuthorizationInfo.addStringPermissions(menuStrings);
                }
            });
            log.info("获取到的role:{}", JSONObject.toJSONString(roleStrings));
            simpleAuthorizationInfo.addRoles(roleStrings);
            return simpleAuthorizationInfo;
        }

        return null;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String account = usernamePasswordToken.getUsername();
        log.info(">>>AuthenticationInfo 获取 account:{}信息", account);
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", account));
        log.info(">>>AuthenticationInfo 获取 sysUser:{}信息", JSONObject.toJSONString(sysUser));
        if (sysUser == null) {
            throw new UnknownAccountException("用户不存在!");
        }
        return new SimpleAuthenticationInfo(sysUser, sysUser.getPassword(), new MyByteSource(sysUser.getSalt()), this.getName());
    }
}
